<template>
  <div class="user">
    <el-breadcrumb separator="/">
  <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
</el-breadcrumb>
<div style="margin-top: 15px;">
  <el-input placeholder="请输入内容" v-model="search"  class="main" @keydown.enter.native="searchUser">
    <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
  </el-input>
  <el-button type="primary" plain class="adduser" @click="addDialogFormVisible = true">添加用户</el-button>
</div>
<el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
  <el-form :model="addForm" ref="addFormRef" :rules="myrules">
    <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
      <el-input v-model="addForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
      <el-input v-model="addForm.password"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
      <el-input v-model="addForm.email"></el-input>
    </el-form-item>
    <el-form-item label="电话" :label-width="formLabelWidth" prop="mobile">
      <el-input v-model="addForm.mobile"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="addDialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitAdd('addFormRef')">确 定</el-button>
  </div>
</el-dialog>

<!--编辑用户-->
<el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
      <el-form :model="editForm" ref="editFormRef" :rules="myrules">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
     <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit('editFormRef')">确 定</el-button>
      </div>
    </el-dialog>
  <template>
  <el-table
    :data="tableData"
    border
    style="width: 100%"
    class="Addtable">
    <el-table-column
      type="index"
      width="50px"
      >
    </el-table-column>
    <el-table-column
      prop="username"
      label="姓名">
    </el-table-column>
    <el-table-column
      prop="email"
      label="邮箱">
    </el-table-column>
    <el-table-column
      prop="mobile"
      label="电话">
    </el-table-column>
    <el-table-column
      label="状态">
      <template slot-scope="scope">
        <el-switch
        @change="toggleState(scope.row)"
  v-model="scope.row.mg_state"
  active-color="#13ce66"
  inactive-color="#ff4949">
</el-switch>
      </template>
    </el-table-column>
    <el-table-column
      label="操作">
      <template slot-scope="scope">
        <el-button type="primary" icon="el-icon-edit" circle @click="handleEditUser(scope.row)"></el-button>
        <el-button type="danger" icon="el-icon-delete" circle @click="handleDelUser(scope.row.id)"></el-button>
        <el-button type="warning" icon="el-icon-check" circle></el-button>
      </template>
    </el-table-column>
  </el-table>
</template>
<!-- 分页 -->
    <el-pagination
      class="page mt-15"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="1"
      :page-sizes="[1, 2, 3, 4]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalnum">
    </el-pagination>
  </div>
</template>
<script>
import { getAdduser, addUser, editDel, editUser, changeState } from '@/api'
export default {
  data () {
    let checkEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入邮箱'))
      } else {
        // 校验邮箱规则
        // eslint-disable-next-line
        let emailReg = /^([a-zA-Z0-9_\.\-])\@(([a-zA-Z0-9\-])\.)([a-zA-Z0-9]{2,4})$/
        if (emailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }
    }
    return {
      search: '',
      tableData: [],
      pagesize: 10, // 每页显示多少条
      pagenum: 1, // 当前页码默认为第一页
      totalnum: 1, // 用户总页数
      addDialogFormVisible: false, // 添加用户对话框的显示于隐藏
      editDialogFormVisible: false,
      formLabelWidth: '80px', // 设置input左侧文字的宽度
      // 添加用户表单的字段
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {
        id: -1,
        username: '',
        password: '',
        mobile: ''
      },
      myrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ]
      }
      // state: ''
    }
  },
  created () {
    this.initAddUser()
  },
  methods: {
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.initAddUser()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.pagenum = val
      this.initAddUser()
    },
    toggleState (row) {
      changeState(row.id, row.mg_state)
        .then(res => {
          this.$message.success(res.meta.msg)
        })
    },

    initAddUser () {
      getAdduser(this.search, this.pagenum, this.pagesize)
        .then(res => {
          console.log(res)
          this.tableData = res.data.users
          this.totalnum = res.data.total
        })
    },
    // 搜索框按钮
    searchUser () {
      // console.log(111)
      this.initAddUser()
      this.search = ''
    },
    // 添加用户按钮
    submitAdd (formRef) {
      this.$refs[formRef].validate((isPass) => {
        if (isPass) {
          addUser(this.addForm)
            .then(res => {
              console.log(res)
              console.log(this)
              if (res.meta.status === 201) {
                this.$message.success('添加用户成功')
                this.addDialogFormVisible = false
                // 清空表单
                this.addForm.username = ''
                this.addForm.password = ''
                this.addForm.email = ''
                this.addForm.mobile = ''
                this.initAddUser()
              }
            })
        } else {
          this.$message.warning('请填写正确的表单')
        }
      })
      // console.log(this)
    },
    handleDelUser (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        editDel(id)
          .then(res => {
            if (res.meta.status = 200) {
              this.initAddUser()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message.error(res.meta.msg)
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleEditUser (row) {
      this.editForm.id = row.id
      this.editForm.username = row.username
      this.editForm.email = row.email
      this.editForm.mobile = row.mobile
      this.editDialogFormVisible = true
    },
    submitEdit (formRef) {
      this.$refs[formRef].validate((isPass) => {
        if (isPass) {
          editUser(this.editForm)
            .then(res => {
              if (res.meta.status === 200) {
                this.$message.success(res.meta.msg)
                this.editDialogFormVisible = false
                this.initAddUser()
              }
            })
        } else {
          this.$message.warning('请填写正确的表单')
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
<style lang="scss" scoped>
.main {
  width: 330px;
}
.adduser {
  margin-left: 10px;
}
.Addtable {
  margin-top: 10px;
}
</style>
